<!--
 * @Description: 会话列表
 * @Author: Kerwin
 * @Date: 2024-09-14 14:11:42
 * @LastEditTime: 2025-04-17 14:30:28
 * @LastEditors:  Please set LastEditors
-->

<template>
    <view class="c_mian" @click="handleClick">
 
        <template v-for="item in latestConversationList" :key="item?.id">
 
            <view class="cItem" :class="[item.isTop ? 'top' : '']" @click="toChat(item)" @longpress="showAction(item)">
                <view class="avatar">
                    <view v-if="item?.unreadMessageCount" class="count"
                        :class="{ 'dot': item.conversationType === RongIMLib.ConversationType.GROUP }">
                        {{ item.conversationType === RongIMLib.ConversationType.PRIVATE ? item.unreadMessageCount : ''
                        }}
                    </view>
                    <u-avatar :src="item?.portraitUri" size="110" mode="square"></u-avatar>
                </view>
                <view class="content">
                    <view class="nameBox">
                        <text class="name">{{ item?.name }}</text>
                        <text class="time">{{ timeDetia(item?.latestMessage!.sentTime, 'MM-DD') }}</text>
                    </view>
                    <view class="latest">
                        <text class="name" v-if="item?.latestMessage?.messageType === MessageType.IMAGE">[图片]</text>
                        <text class="name" v-else-if="item?.latestMessage?.messageType === MessageType.LOCATION">[位置]{{
                            item?.latestMessage?.content?.content }}</text>
                        <text class="name" v-else>{{ item?.latestMessage?.content?.content }}</text>
                    </view>
                </view>
                <view class="action" v-if="item.showAction">
                    <view class="aItem" @click.stop="toDel(item)">删除该聊天</view>
                    <view class="aItem" @click.stop="toTop(item)">{{ item.isTop ? '取消置顶' : '置顶该聊天' }} </view>
                </view>
            </view>
        </template>
    </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, watch } from 'vue';
import { storeToRefs } from 'pinia'
import { useUserStore, useChatStore } from '@/store'
import { getImgFullPath, dateFormat } from '@/utils'
import { timeDetia } from '@/utils/common'
import { route } from '@/utils/common';
import { socialApi } from '@/api';
import Conversation from './conversation.vue';
import RongIMLib from '@/packageD/common/rongCloud/im_init';
import { MessageType } from '@rongcloud/imlib-next';


const userStore = useUserStore()
const chatStore = useChatStore()
const { latestConversationList } = storeToRefs(chatStore)

watch(latestConversationList, (newVal, oldVal) => {
    if (newVal) {
        console.log('watch latestConversationList ==>',latestConversationList.value)
        formatConversationList()
    }
}, { deep: true })

function conversationSort() {
    latestConversationList.value.sort((a, b) => {
        if (a.isTop && !b.isTop) {
            return -1;
        }
        if (!a.isTop && b.isTop) {
            return 1;
        }
        return 0;
    });
}
// 格式化会话列表
function formatConversationList() {
    // 按照置顶排序
    conversationSort()
    // 获取头像昵称等信息
    latestConversationList.value.forEach((item: { conversationType: RongIMLib.ConversationType; name?: string; portraitUri?: string; }) => {
       console.log('会话类型',item?.conversationType,item);
       
        if (item?.conversationType === RongIMLib.ConversationType.PRIVATE) {
            if (item.name || item.portraitUri) return
            getUserProfile(item)
        } else if (item?.conversationType === RongIMLib.ConversationType.GROUP) {
            getGroupProfile(item)
        }
    })
}
async function getUserProfile(item: { conversationType?: RongIMLib.ConversationType; targetId?: any; name?: any; portraitUri?: any; }) {
    const res = await chatStore.getUserProfiles([item.targetId])
    console.log('getUserProfile==>', res)
    if (res.data && res.data?.length) {
        const { name, portraitUri } = res.data[0]
        nextTick(() => {
            item.name = name
            if (portraitUri && portraitUri.startsWith('//')) {
                item.portraitUri = 'https:' + portraitUri;
            } else {
                portraitUri && (item.portraitUri = getImgFullPath(portraitUri))
            }
        })
    }
}
async function getGroupProfile(item: { conversationType?: RongIMLib.ConversationType; targetId?: any; name?: any; portraitUri?: any; }) {
    const { data } = await socialApi.circleInfo({ id: item.targetId })
    if (data) {
        nextTick(() => {
            item.name = data.name
            item.portraitUri = getImgFullPath(data.avatar)
        })
    }
}

// 长按事件
function showAction(item: { showAction: boolean; }) {
    hideActions()
    item.showAction = true
}
function handleClick() {
    hideActions()
}
function hideActions() {
    latestConversationList.value.forEach((item: { showAction: boolean; }) => {
        item.showAction = false
    })
}

// 删除聊天
async function toDel(item: { targetId: string; conversationType: RongIMLib.ConversationType; showAction?: boolean;uState:boolean; }) {
    item.showAction = false
    chatStore.removeConversation(item.targetId, item.conversationType,true)
}

// 置顶聊天
async function toTop(item: { targetId: any; conversationType: RongIMLib.ConversationType; isTop?: boolean; showAction?: boolean; }) {
    const res = await chatStore.setConversationToTop(item.targetId, item.conversationType, !item.isTop)
    if (res.code === 0) {
        item.showAction = false
        const itemIdx = latestConversationList.value.findIndex((item: { targetId: any; }) => item.targetId)
        item.isTop = !item.isTop
        latestConversationList.value.splice(0, 0, latestConversationList.value.splice(itemIdx, 1)[0]);
        conversationSort()
    }
}
// 清除指定会话未读消息
async function clearMessagesUnreadStatus(item: { targetId?: any; name?: any; conversationType?: any; unreadMessageCount?: any; }) {
    const { targetId, conversationType } = item
    const res = await chatStore?.clearMessagesUnreadStatus(
        targetId,
        conversationType
    )
    item.unreadMessageCount = 0
    console.log(res)
}

interface Conversation {
    id: number
    name: string
    avatar: string
    createTime: number
    remark: string
    chatGroupId?: number,
    type?: any,
    targetId?: any,
    portraitUri?: string,
    conversationType: RongIMLib.ConversationType
}
const conversationList = reactive<Conversation[]>([])

// function getCache() {
//     for (let key in latestConversationList.value) {
//         conversationList.push(latestConversationList.value[key])
//     }
// }
// getCache()

function toChat(item: {
    type?: any
    chatGroupId?: any
    id?: any
    targetId?: any,
    name?: any,
    portraitUri?: string,
    conversationType: RongIMLib.ConversationType.GROUP
}) {

console.log('群聊===》',RongIMLib.ConversationType.GROUP,item);
    clearMessagesUnreadStatus(item)
    route({
        url: '/packageD/pages/chat/index',
        params: {
            targetId: item.id || item.targetId,
            userId: item.targetId,
            name: item.name,
            cid: item.id,
            type: item.type,
            conversationType: item.conversationType || RongIMLib.ConversationType.GROUP
        }
    })
}
async function getGroupList() {
    uni.showLoading()
    const { data } = await socialApi.getUserChatGroup({
        userId: userStore?.userInfo?.id,
        noPaging: true
    }).finally(() => {
        uni.hideLoading()
    })
    console.log('获取用户全部群聊==>', data);

    conversationList.push(...data)
    // latestConversationList.value.push(...data)

}

 


onMounted(() => {
    console.log('获取群xxxxxxxxxxxxx',latestConversationList.value)
    if (conversationList.length === 0) {
        getGroupList()
    }
})

</script>

<style lang="scss" scoped>
@import '@/styles/helper.scss';


.c_mian {
    flex: 1;

    .cItem {
        display: flex;
        flex: 1;
        width: 100%;
        padding: 20rpx;
        box-sizing: border-box;
        background: #fff;
        position: relative;

        .avatar {
            position: relative;

            .count {
                position: absolute;
                width: 24rpx;
                height: 24rpx;
                right: 0;
                top: 0;
                transform: translate(40%, -40%);
                display: flex;
                justify-content: center;
                align-items: center;
                background-color: red;
                color: #fff;
                border-radius: 50%;
                z-index: 1;
                font-size: 20rpx;

                &.dot {
                    width: 16rpx;
                    height: 16rpx;
                }
            }
        }

        &.top {
            background: #f5f5f5;
        }

        .action {
            position: absolute;
            right: 20%;
            top: 50%;
            display: flex;
            flex-direction: column;
            background: #fff;
            box-shadow: 0 0 16rpx 0rpx rgba(0, 0, 0, 0.1);
            padding: 10rpx 20rpx;
            z-index: 10;

            .aItem {
                display: flex;
                align-items: center;
                justify-content: flex-start;
                font-size: 28rpx;
                line-height: 70rpx;
            }
        }

        .content {
            flex: 1;
            margin-left: 20rpx;
            min-height: 140rpx;
            border-bottom: 1rpx solid #eeeeeed0;

            .nameBox {
                display: flex;
                justify-content: space-between;

                .name {
                    font-size: 30rpx;
                    max-width: 340rpx;
                    @include ellipsis;
                }

                .time {
                    color: #999;
                }

                margin-bottom: 20rpx;
            }

            .latest {
                .lastContent {
                    color: #c5c1c1
                }

            }

            .actions {
                display: flex;
                align-items: center;
                justify-content: flex-end;
                gap: 20rpx;

                .tips {
                    color: #999;
                }
            }
        }
    }
}
</style>